//
//  ESJokesSearchViewController.m
//  EasyStyle
//
//  Created by FK on 16/5/14.
//  Copyright © 2016年 FK. All rights reserved.
//

#import "ESJokesSearchViewController.h"
#import "ESNavigationController.h"
#import "ESLaetedJokesSearchDetailCell.h"
#import "ESJokesNetResult.h"
#import "ESMainNetTaskManager.h"
#import "MJRefresh.h"


static NSString * const kESJokesSearchVCLastedUpdateTimeKey = @"ESJokesSearchVC_MJMJRefresh_LastedUpdateTime";

@interface ESJokesSearchViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *searchResultList;

@end


static NSInteger pageNum = 2;

@implementation ESJokesSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupRootView];
    
    [self setupRefresh];
    

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (_tableView) {
        [self loadData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 加载数据
- (void)loadData
{
//    ESWeChatDAO *dao = [ESWeChatDAO shareInstance];
//    _newsList = nil;
//    _newsList = [dao queryAllFromDB];
    
    if (![self canUpdateNewsList]) {
        if (_searchResultList != nil && _searchResultList.count > 0) {
            [self.tableView reloadData];
        } else {
//            [self.loadingView setLoadingState:1];
            [self refreshData];
        }
    } else {
        [self refreshData];
    }
}


#pragma mark -- 布局相关
- (void)setupRootView
{
    
    self.view.backgroundColor = [UIColor cyanColor];
    
    WS(weakSelf);
    self.navigationController.navigationBarHidden = YES;
    [self addCustomNavigationBarWithStyle:DefaultStyle customColor:[UIColor colorWithHex:@"3ec5dc"]];
    [self.sgCustomNavigationBar showBackButtonWithActionBlock:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    [self.sgCustomNavigationBar setTitle:@"趣事+"];
    self.sgCustomNavigationBar.titleLabel.textColor = [UIColor whiteColor];
    
//    [(ESNavigationController *)self.navigationController registerClass:[self class]];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.sgCustomNavigationBar.height, self.view.width, self.view.height-self.sgCustomNavigationBar.height) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.showsVerticalScrollIndicator = YES;
    //    _tableView.separatorInset = UIEdgeInsetsMake(0,13,0,13);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
}

- (void)setupRefresh
{
    WS(weakSelf);
    //下拉刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf startNetTaskWithIsHeaderUpdate:YES];
    }];
    [header setTitle:@"再拉一点 给你好看" forState:MJRefreshStateIdle];
    [header setTitle:@"松手 给你好看" forState:MJRefreshStatePulling];
    [header setTitle:@"稍等!只为给你更好的" forState:MJRefreshStateRefreshing];
    [header setTitle:@"别拉了 好看的都在这了" forState:MJRefreshStateNoMoreData];
    _tableView.mj_header = header;
    
    // 上拉加载更多
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf startNetTaskWithIsHeaderUpdate:NO];
    }];
    [footer setTitle:@"再拉一点 给你好看" forState:MJRefreshStateIdle];
    [footer setTitle:@"松手 给你好看" forState:MJRefreshStatePulling];
    [footer setTitle:@"稍等!只为给你更好的" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"别拉了 好看的都在这了" forState:MJRefreshStateNoMoreData];
    _tableView.mj_footer = footer;
}


#pragma mark -- 网络相关
- (void)startNetTaskWithIsHeaderUpdate:(BOOL)headerUpdate
{
    headerUpdate?(pageNum = 2):(pageNum++);
    
    WS(weakSelf);
    ESMainNetTaskManager *netTask = [ESMainNetTaskManager new];
    [netTask setBlockWithReturnBlock:^(id returnValue) {
        
        ESJokesNetResult *jokesNetResult = [ESJokesNetResult new];
        
        if ([returnValue isKindOfClass:[NSArray class]]) {
            if (headerUpdate) {
                
                
                
                weakSelf.searchResultList = nil;
                weakSelf.searchResultList = [jokesNetResult getLastedJokesData:returnValue];
            } else {
                [weakSelf.searchResultList addObjectsFromArray:[jokesNetResult getLastedJokesData:returnValue]];
            }
            
            [weakSelf.tableView reloadData];
            
            // 结束刷新
            [weakSelf.tableView.mj_header endRefreshing];
            // 结束刷新
            [weakSelf.tableView.mj_footer endRefreshing];
            
            //        if (weakSelf.loadingView != nil && !weakSelf.loadingView.hidden) {
            //            weakSelf.loadingView.hidden = YES;
            //        }
        }

    } WithErrorBlock:^(id errorCode) {
        
        ESNetResult *error = (ESNetResult *)errorCode;
        
        NSString *errorReason = [NSString stringWithFormat:@"%@",error.reason];
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:errorReason message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
    } WithFailureBlock:^{
        // 结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        // 结束刷新
        [weakSelf.tableView.mj_footer endRefreshing];
        
    }];
    
    [netTask loadCardJokesDataWithPageNum:pageNum];
}

#pragma mark -- 事件相关
- (void)refreshData
{
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_header.lastUpdatedTimeKey = kESJokesSearchVCLastedUpdateTimeKey;
}

#pragma mark -- 辅助函数
// 根据上次刷新时间判断现在是否自动刷新   大于2小时则自动刷新
- (BOOL)canUpdateNewsList
{
    MJRefreshHeader *header = [MJRefreshHeader new];
    header.lastUpdatedTimeKey = kESJokesSearchVCLastedUpdateTimeKey;
    NSDate *lastUpdateTime = header.lastUpdatedTime;
    
    if (lastUpdateTime == nil) {
        return NO;
    }
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
    NSDateComponents *maxDateComponent = [[NSDateComponents alloc] init];
    [maxDateComponent setHour:2];
    NSDate *maxDepartDate = [calendar dateByAddingComponents:maxDateComponent toDate:lastUpdateTime options:0];
    
    NSDate *now = [NSDate date];
    if ([now compare:maxDepartDate] == NSOrderedAscending || [now compare:maxDepartDate] == NSOrderedSame) {
        return NO;
    }
    
    return YES;
}


#pragma mark -- UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_searchResultList != nil && _searchResultList.count > 0) {
        return _searchResultList.count;
    } else {
        return 0;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 
    
    ESLaetedJokesSearchDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ESLaetedJokesSearchDetailCell"];
    if (cell == nil) {
        cell = [ESLaetedJokesSearchDetailCell loadViewFromSameXibName];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    cell.jokesItem = [_searchResultList objectAtIndex:indexPath.row];
    return cell;
}


#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LastedjokesItem *item = [_searchResultList objectAtIndex:indexPath.row];
    CGFloat ss= [ESLaetedJokesSearchDetailCell getHeightCellWithContent:item.content];
    return ss;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


@end
